package com.xsq.rpc.provider.register;


import com.xsq.rpc.provider.register.scanner.RPCProviderXsqServiceClassPathSacnner;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;


/**
 * @ClassName BeanRegister
 * @Description 把不受spring管理的类加入到spring管理中
 * @Author xsq
 * @Date 2020/5/30 11:38
 **/

public class BeanProviderRegister implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware {

    private ResourceLoader resourceLoader;

    private BeanFactory beanFactory;

    private Environment environment;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }


    /**
     * 把我们自定义注解修饰的bean注入到spring容器中
     *
     * @param importingClassMetadata
     * @param registry
     */

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //但是有一个问题，我们并不知道需要register哪些bean,所以这里要用到继承ClassPathBeanDefinitionScanner的自定义scanner
        RPCProviderXsqServiceClassPathSacnner scanner = new RPCProviderXsqServiceClassPathSacnner(registry);
        scanner.setResourceLoader(resourceLoader);
        //核心代码,使知道需要register哪个注解修饰的bean
        scanner.registerFilters();
        //需要扫描注册的包的泛微
        scanner.scan("com.xsq.rpc");
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}

